<?php

namespace app\service\http\docspace;

use hunma\exception\ApiException;
use hunma\utils\guzzle\BaseHttpClient;

/**
 * Docspace API 客户端
 * - 提供通过URL上传到OSS的接口封装
 */
class DocspaceApiClient extends BaseHttpClient
{
    /**
     * API 基础URL
     * @var string
     */
    protected $baseUrl;

    public function __construct(array $config = [], array $defaultOptions = [])
    {
        $this->baseUrl = getenv('DOCSPACE_API_URL') ?: 'http://127.0.0.1:8789';
        parent::__construct($config, $defaultOptions);
    }

    /**
     * 通过远程URL上传文件到OSS（调用 docspace /api/upload-url）
     *
     * @param string $url 远程图片/文件URL
     * @param array $headers 额外请求头
     * @return string 最终可访问URL（STATIC_URL/DCDN域名）
     * @throws ApiException
     */
    public function uploadByUrl(string $url, array $headers = []): string
    {
        if (!preg_match('#^https?://#i', $url)) {
            throw new ApiException('仅支持http/https远程URL');
        }

        $endpoint = $this->buildUrl('/api/upload-url');
        $data = [
            'url' => $url,
        ];

        $resp = $this->postJson($endpoint, $data, $headers);
        // 预期返回 { code:200, data: "https://static.../path" }
        if (is_array($resp)) {
            if (isset($resp['code']) && (int)$resp['code'] === 200) {
                $data = $resp['data'] ?? null;
                if (is_string($data)) {
                    return $data;
                }
            }
        }
        throw new ApiException('Docspace 上传失败', $resp);
    }

    /**
     * 构建完整URL
     */
    protected function buildUrl(string $endpoint): string
    {
        if (strpos($endpoint, 'http://') === 0 || strpos($endpoint, 'https://') === 0) {
            return $endpoint;
        }
        if (strpos($endpoint, '/') !== 0) {
            $endpoint = '/' . $endpoint;
        }
        return rtrim($this->baseUrl, '/') . $endpoint;
    }
}
